package com.example.triprec.dao;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.text.TextUtils;

import com.example.triprec.common.Result;
import com.example.triprec.common.ScenicData;
import com.example.triprec.entity.Comment;
import com.example.triprec.entity.Trip;
import com.example.triprec.entity.User;
import com.example.triprec.utils.SqliteUtils;
import com.gzone.university.utils.DateUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 行程数据访问对象
 */
@SuppressLint("Range")
public class TripDao {

    /**
     * 添加行程
     */
    public static Result<Trip> addTrip(Trip trip) {
        if (trip == null || trip.getUserId() == null || trip.getScenicId() == null
                || TextUtils.isEmpty(trip.getTripName()) || TextUtils.isEmpty(trip.getStartDate())) {
            return new Result<>(false, "行程信息不完整", null);
        }

        String currentTime = DateUtils.format(new Date());
        trip.setCreateTime(currentTime);

        // 默认状态为未开始
        if (trip.getStatus() == null) {
            trip.setStatus(0);
        }

        ContentValues values = new ContentValues();
        values.put("user_id", trip.getUserId());
        values.put("scenic_id", trip.getScenicId());
        values.put("trip_name", trip.getTripName());
        values.put("start_date", trip.getStartDate());
        if (!TextUtils.isEmpty(trip.getEndDate())) {
            values.put("end_date", trip.getEndDate());
        }
        values.put("create_time", trip.getCreateTime());
        values.put("status", trip.getStatus());

        long id = SqliteUtils.getInstance().getWritableDatabase().insert("tb_trip", null, values);
        if (id > 0) {
            trip.setId(id);
            return new Result<>(true, "添加行程成功", trip);
        }
        return new Result<>(false, "添加行程失败", null);
    }

    /**
     * 更新行程
     */
    public static Result<Void> updateTrip(Trip trip) {
        if (trip == null || trip.getId() == null) {
            return new Result<>(false, "行程ID不能为空", null);
        }

        ContentValues values = new ContentValues();

        if (!TextUtils.isEmpty(trip.getTripName())) {
            values.put("trip_name", trip.getTripName());
        }

        if (!TextUtils.isEmpty(trip.getStartDate())) {
            values.put("start_date", trip.getStartDate());
        }

        if (trip.getEndDate() != null) {
            values.put("end_date", trip.getEndDate());
        }

        if (trip.getStatus() != null) {
            values.put("status", trip.getStatus());
        }

        int i = SqliteUtils.getInstance().getWritableDatabase().update("tb_trip", values, "id=?", new String[]{String.valueOf(trip.getId())});
        if (i > 0) {
            return new Result<>(true, "更新行程成功", null);
        }
        return new Result<>(false, "更新行程失败", null);
    }

    /**
     * 根据用户ID查询行程数量
     */
    public static Result<Integer> getTripCountByUserId(Long userId) {
        if (userId == null) {
            return new Result<>(false, "用户ID不能为空", null);
        }

        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query("tb_trip", null, "user_id=?", new String[]{String.valueOf(userId)}, null, null, null);
        int count = cursor.getCount();
        cursor.close();

        return new Result<>(true, "查询成功", count);
    }

    /**
     * 删除行程
     */
    public static Result<Void> deleteTrip(Long tripId) {
        if (tripId == null) {
            return new Result<>(false, "行程ID不能为空", null);
        }

        int i = SqliteUtils.getInstance().getWritableDatabase().delete("tb_trip", "id=?", new String[]{String.valueOf(tripId)});
        if (i > 0) {
            return new Result<>(true, "删除行程成功", null);
        }
        return new Result<>(false, "删除行程失败", null);
    }

    /**
     * 根据行程ID查询行程
     */
    public static Result<Trip> getTripById(Long tripId) {
        if (tripId == null) {
            return new Result<>(false, "行程ID不能为空", null);
        }

        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query("tb_trip", null, "id=?", new String[]{String.valueOf(tripId)}, null, null, null);
        if (cursor.moveToNext()) {
            Trip trip = extractTripFromCursor(cursor);
            cursor.close();

            // 关联用户信息
            Result<User> userResult = UserDao.getByUserId(trip.getUserId());
            if (userResult.isSuccess()) {
                trip.setUser(userResult.getData());
            }

            // 关联景点信息
            trip.setScenic(ScenicData.getScenicById(trip.getScenicId()));

            // 关联评论信息
            Result<Comment> commentResult = CommentDao.getByTripId(trip.getId());
            if (commentResult.isSuccess()) {
                trip.setComment(commentResult.getData());
            }

            return new Result<>(true, "查询成功", trip);
        }
        cursor.close();
        return new Result<>(false, "行程不存在", null);
    }

    /**
     * 获取用户所有行程
     */
    public static Result<List<Trip>> getTripsByUserId(Long userId) {
        if (userId == null) {
            return new Result<>(false, "用户ID不能为空", null);
        }

        List<Trip> tripList = new ArrayList<>();
        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query("tb_trip", null, "user_id=?", new String[]{String.valueOf(userId)}, null, null, "start_date ASC");

        while (cursor.moveToNext()) {
            Trip trip = extractTripFromCursor(cursor);

            // 关联用户信息
            Result<User> userResult = UserDao.getByUserId(trip.getUserId());
            if (userResult.isSuccess()) {
                trip.setUser(userResult.getData());
            }

            // 关联景点信息
            trip.setScenic(ScenicData.getScenicById(trip.getScenicId()));

            // 关联评论信息
            Result<Comment> commentResult = CommentDao.getByTripId(trip.getId());
            if (commentResult.isSuccess()) {
                trip.setComment(commentResult.getData());
            }

            tripList.add(trip);
        }
        cursor.close();

        if (!tripList.isEmpty()) {
            return new Result<>(true, "查询成功", tripList);
        } else {
            return new Result<>(true, "暂无行程", tripList);
        }
    }

    /**
     * 根据景点ID查询行程
     */
    public static Result<List<Trip>> getTripsByScenicId(Long scenicId) {
        if (scenicId == null) {
            return new Result<>(false, "景点ID不能为空", null);
        }

        List<Trip> tripList = new ArrayList<>();
        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query("tb_trip", null, "scenic_id=?", new String[]{String.valueOf(scenicId)}, null, null, "start_date ASC");

        while (cursor.moveToNext()) {
            Trip trip = extractTripFromCursor(cursor);

            // 关联用户信息
            Result<User> userResult = UserDao.getByUserId(trip.getUserId());
            if (userResult.isSuccess()) {
                trip.setUser(userResult.getData());
            }

            // 关联景点信息
            trip.setScenic(ScenicData.getScenicById(trip.getScenicId()));

            // 关联评论信息
            Result<Comment> commentResult = CommentDao.getByTripId(trip.getId());
            if (commentResult.isSuccess()) {
                trip.setComment(commentResult.getData());
            }

            tripList.add(trip);
        }
        cursor.close();

        if (!tripList.isEmpty()) {
            return new Result<>(true, "查询成功", tripList);
        } else {
            return new Result<>(true, "暂无行程", tripList);
        }
    }

    /**
     * 获取用户的未来行程（状态为未开始的）
     */
    public static Result<List<Trip>> getFutureTripsByUserId(Long userId) {
        if (userId == null) {
            return new Result<>(false, "用户ID不能为空", null);
        }

        List<Trip> tripList = new ArrayList<>();
        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query("tb_trip", null, "user_id=? AND status=0", new String[]{String.valueOf(userId)}, null, null, "start_date ASC");

        while (cursor.moveToNext()) {
            Trip trip = extractTripFromCursor(cursor);

            // 关联用户信息
            Result<User> userResult = UserDao.getByUserId(trip.getUserId());
            if (userResult.isSuccess()) {
                trip.setUser(userResult.getData());
            }

            // 关联景点信息
            trip.setScenic(ScenicData.getScenicById(trip.getScenicId()));

            // 关联评论信息
            Result<Comment> commentResult = CommentDao.getByTripId(trip.getId());
            if (commentResult.isSuccess()) {
                trip.setComment(commentResult.getData());
            }

            tripList.add(trip);
        }
        cursor.close();

        if (!tripList.isEmpty()) {
            return new Result<>(true, "查询成功", tripList);
        } else {
            return new Result<>(true, "暂无未来行程", tripList);
        }
    }

    /**
     * 获取用户的已完成行程（状态为已完成的）
     */
    public static Result<List<Trip>> getCompletedTripsByUserId(Long userId) {
        if (userId == null) {
            return new Result<>(false, "用户ID不能为空", null);
        }

        List<Trip> tripList = new ArrayList<>();
        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query("tb_trip", null, "user_id=? AND status=1", new String[]{String.valueOf(userId)}, null, null, "start_date ASC");

        while (cursor.moveToNext()) {
            Trip trip = extractTripFromCursor(cursor);

            // 关联用户信息
            Result<User> userResult = UserDao.getByUserId(trip.getUserId());
            if (userResult.isSuccess()) {
                trip.setUser(userResult.getData());
            }

            // 关联景点信息
            trip.setScenic(ScenicData.getScenicById(trip.getScenicId()));

            // 关联评论信息
            Result<Comment> commentResult = CommentDao.getByTripId(trip.getId());
            if (commentResult.isSuccess()) {
                trip.setComment(commentResult.getData());
            }

            tripList.add(trip);
        }
        cursor.close();

        if (!tripList.isEmpty()) {
            return new Result<>(true, "查询成功", tripList);
        } else {
            return new Result<>(true, "暂无已完成行程", tripList);
        }
    }

    /**
     * 从游标中提取行程信息
     */
    private static Trip extractTripFromCursor(Cursor cursor) {
        Trip trip = new Trip();
        trip.setId(cursor.getLong(cursor.getColumnIndex("id")));
        trip.setUserId(cursor.getLong(cursor.getColumnIndex("user_id")));
        trip.setScenicId(cursor.getLong(cursor.getColumnIndex("scenic_id")));
        trip.setTripName(cursor.getString(cursor.getColumnIndex("trip_name")));
        trip.setStartDate(cursor.getString(cursor.getColumnIndex("start_date")));

        if (!cursor.isNull(cursor.getColumnIndex("end_date"))) {
            trip.setEndDate(cursor.getString(cursor.getColumnIndex("end_date")));
        }

        trip.setCreateTime(cursor.getString(cursor.getColumnIndex("create_time")));
        trip.setStatus(cursor.getInt(cursor.getColumnIndex("status")));

        return trip;
    }
} 